package c926.xiaoduyun.xiaodu.mservice;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DB;
import kd.bos.db.DBRoute;
import kd.bos.entity.BadgeInfo;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.exception.KDBizException;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.BillList;
import kd.bos.list.IListView;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DBServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.util.CollectionUtils;
import kd.sdk.plugin.Plugin;
import org.jetbrains.annotations.NotNull;

import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Date;
import java.util.EventObject;
import java.util.Set;

/**
 * 开始消毒表单插件
 */
public class XiaoduApplyStartWorkPlugin extends AbstractListPlugin implements Plugin {
    @Override
    public void registerListener(EventObject e) {
        // 工具栏项注册点击监听
        Toolbar toolbar = this.getView().getControl("toolbarap");
        toolbar.addItemClickListener(this);
    }

    /**
     * 点击【开始消毒】之前需要进行校验
     * 1.是否选中数据
     * 2.选择的数据是否是已审核状态
     * 3.当前登录人是否是申请人
     * 4.是否是消毒申请进入时间当天
     *
     * @param evt
     */
    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if ("c926_startxiaodu".equalsIgnoreCase(itemKey)) {
            // 获取所选列表数据
            BillList billList = this.getView().getControl("billlistap");
            ListSelectedRowCollection selectedRow = billList.getSelectedRows();
            if (selectedRow.size() != 1) {
                return;
            }
            DynamicObject loaded = BusinessDataServiceHelper.loadSingle(selectedRow.get(0).getPrimaryKeyValue(), "c926_xiaoduapply");
            String billstatus = (String) loaded.get("billstatus");
            Date inTime = (Date) loaded.get("c926_applyintime");
            long applyuser = (long) loaded.get("c926_applyuser.id");
            long currentUserId = UserServiceHelper.getCurrentUserId();
            if (!"C".equals(billstatus)) {
                this.getView().showTipNotification("请选择已审核的申请单");
                evt.setCancel(true);
                return;
            }
            // 获取当前日期
            Date currentDate = getDate();
            // 检查申请日期是否是今天
            if (!currentDate.equals(inTime)) {
                this.getView().showTipNotification("申请日期当天才能开始消毒");
                evt.setCancel(true);
                return;
            }
            // 检查当前登录用户是否是申请人
            if (applyuser != currentUserId) {
                this.getView().showTipNotification("你不是申请进入车间的人员，没有权限进行消毒！");
                evt.setCancel(true);
                return;
            }
        }
        super.beforeItemClick(evt);
    }

    /**
     * 点击【开始消毒】
     * 1.获取当前选择的数据信息
     * 2.拿到当前数据中申请进入的车间信息
     * 3.查询当前车间是否有匹配的消毒方案
     * 3.1 没有-提示：请先为该车间分配方案
     * 3.2 有-获取当前车间匹配的消毒方案信息，组装消毒记录单信息
     * 4.消毒记录单生成后，消毒记录单的状态变成进行中，人员申请单的单据状态变成消毒中。
     * 5.消毒记录单步骤分录的第一条分录消毒状态为进行中，其他分录的消毒状态为未进行。
     */
    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if ("c926_startxiaodu".equalsIgnoreCase(itemKey)) {
            // 获取所选列表数据
            BillList billList = this.getView().getControl("billlistap");
            ListSelectedRowCollection selectedRow = billList.getSelectedRows();
            DynamicObject loaded = BusinessDataServiceHelper.loadSingle(selectedRow.get(0).getPrimaryKeyValue(), "c926_xiaoduapply");
            Object orgfield = loaded.get("c926_orgfield.id");// 车间信息
            // 查询当前车间是否有匹配的消毒方案
            QFilter filter = new QFilter("c926_orgfield", QCP.equals, orgfield).and("status", QCP.equals, "A");
            DynamicObject schemes = BusinessDataServiceHelper.loadSingle("c926_scheme", "id,number,c926_orgfield", new QFilter[]{filter});
            if (schemes == null) {
                this.getView().showTipNotification("请先为该车间分配方案");
                return;
            } else {
                // 执行消毒记录单生成
                pushAndsaveRecord(selectedRow, loaded);
                this.getView().showSuccessNotification("开始消毒成功");
                this.getView().updateView();
            }
        }
        super.itemClick(evt);
    }

    private static void pushAndsaveRecord(ListSelectedRowCollection selectedRow, DynamicObject loaded) {
        // 生成下推参数PushArgs
        PushArgs pushArgs = new PushArgs();
        // 必选，源单标识
        pushArgs.setSourceEntityNumber("c926_xiaoduapply");
        // 必选，目标单标识
        pushArgs.setTargetEntityNumber("c926_xiaodurecord");
        // 可选，自动保存
        pushArgs.setAutoSave(true);
        // 可选，设置单据转换规则的id，如果没有设置，会自动匹配一个规则进行转换
        pushArgs.setRuleId("2022590235833024512");
        // 是否输出详细错误报告
        pushArgs.setBuildConvReport(false);
        // 必选，设置需要下推的源单及分录内码
        pushArgs.setSelectedRows(selectedRow);
        // 调用下推引擎，下推目标单并保存
        ConvertOperationResult pushResult = ConvertServiceHelper.pushAndSave(pushArgs);
        if (pushResult.isSuccess()) {
            System.out.println("DemoBOTPWorkflowPlugin: c926_xiaoduapply 转换c926_xiaodurecord 成功");
            Set<Object> targetBillSet = pushResult.getTargetBillIds();
            long billId = 0L;
            for (Object o : targetBillSet) {
                if (o instanceof Long) {
                    billId = (Long) o;
                }
            }
            QFilter recordFilter = new QFilter("id", QCP.equals, billId);
            DynamicObject record = BusinessDataServiceHelper.loadSingle("c926_xiaodurecord", recordFilter.toArray());
            Object recordBillNo = record.get("billno");
            loaded.set("c926_xiaoduid", recordBillNo);
            loaded.set("billstatus", "D");
            SaveServiceHelper.update(loaded);
            System.out.println("Plugin：下推成功，目标单id：" + billId);
            // 目标单据体赋值
            long schemeId = record.getLong("c926_scheme.id");
            DynamicObject scheme4Db = BusinessDataServiceHelper.loadSingle(schemeId, "c926_scheme");
            DynamicObjectCollection levels = scheme4Db.getDynamicObjectCollection("c926_levelentity");
            DynamicObjectCollection recordStep = record.getDynamicObjectCollection("c926_record_step");
            recordStep.clear();
            for (int i = 0; i < levels.size(); i++) {
                DynamicObject level = levels.get(i);
                DynamicObject rs = recordStep.addNew();
                rs.set("c926_level", level.get("c926_level"));
                DynamicObjectCollection steps = level.getDynamicObjectCollection("c926_stepentity");
                if (CollectionUtils.isEmpty(steps)) {
                    throw new KDBizException("消毒步骤数据不存在");
                }
                DynamicObject setp = steps.get(0);
                rs.set("c926_step", setp.get("c926_xiaodustep"));
                rs.set("c926_status", i == 0 ? "B" : "A");
            }
            SaveServiceHelper.save(new DynamicObject[]{record});
        } else {
            System.out.println("Plugin: c926_xiaoduapply 转换c926_xiaodurecord 失败");
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        Toolbar toolbar = this.getView().getControl("toolbarap");
        IListView listView = (IListView) this.getView();
        ListSelectedRowCollection s = listView.getCurrentListAllRowCollection();
        int count = 0;
        for (ListSelectedRow x : s) {
            if ("C".equals(x.getBillStatus())) {
                count = count + 1; // 计算审核通过的单据数
            }
        }
        //徽标对象
        BadgeInfo info = new BadgeInfo();
        info.setColor("#ff0000");
        info.setCount(count);
        info.setShowZero(true);
        toolbar.setBadgeInfo("c926_startxiaodu", info); // 给关闭按钮设置徽标
    }


    @NotNull
    private static Date getDate() {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        return today.getTime();
    }
}